package demo1;

import java.io.*;
import java.util.Scanner;

import static demo1.Test.scanner;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-10-07
 * Time: 16:15
 */
public class Text3 {

    static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.println("请输入要查找的跟目录：");
        File rootpath = new File(scanner.nextLine());
        System.out.println("请输入要查找的关键词：");
        String word = scanner.nextLine();
        if(!rootpath.isDirectory()){
            System.out.println("该根目录不合法");
            return;
        }
        show(rootpath, word);
    }
    public static void show(File file, String word){
        File[] files = file.listFiles();
        if(files == null || files.length == 0){
            return;
        }
        for (File f : files){
            if (f.isFile()){
                search(f, word);
            }else {
                show(f, word);
            }
        }
    }

    public static void search(File file, String word){
        if(file.getName().contains(word)){
            System.out.println(file.getName());
            return;
        }
        try(InputStream inputStream = new FileInputStream(file)) {
            Scanner scanner = new Scanner(inputStream);
            while (scanner.hasNext()){
                String str = scanner.nextLine();
                if(str.contains(word)){
                    System.out.println(file.getName());
                    return;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
